package web_hr;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

/**
 * Servlet implementation class CheckRegister
 */
@WebServlet("/CheckRegister")
public class CheckRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");		
		String password = request.getParameter("password");
		String bsalary = request.getParameter("basic_salary");
		String fname = request.getParameter("fname");
		String lname = request.getParameter("lname");
		String age = request.getParameter("age");
		String role = request.getParameter("role");
		String sex = request.getParameter("sex");
		boolean flag = true;
		String str = "\\w{1,20}";
		if((!username.matches(str))||(!fname.matches(str))||(!lname.matches(str))){
			flag=false;
		}
		
		String pw = "\\d{1,20}";
		if(!password.matches(pw)){
			flag=false;
		}
		
		String bs = "\\d+\\.?\\d*";
		if((!bsalary.matches(bs))||(role==null)){
			flag = false;
		}
		
		Model m=new Model("hr_employee");
		
		if(flag==true){
		  int n_insert = m.eUpdate("insert into HR_EMPLOYEE values(null,'"+username+"','"+password+"',"+bsalary+",'"+lname+"','"+fname+"','"+age+"','"+role+"','"+sex+"','1')");
		  if(n_insert==1){
			  HttpSession session = request.getSession(true);
			  session.setAttribute("username",username);
			  request.setAttribute("message","Register sucessfully!");
			  request.setAttribute("url","create.jsp");
			  request.getRequestDispatcher("/redirect.jsp").forward(request,response);
		  }
		}else{
			request.setAttribute("message","Information Error<br/>Please check your information!");
			request.setAttribute("url","create.jsp");
			request.getRequestDispatcher("/redirect.jsp").forward(request,response);
		}
		
	}
}
